<template>
  <div class="user-stats-chart">
    <div class="stats-header">
      <h3>数据统计</h3>
      <div class="chart-tabs">
        <a-button :type="activeChart === 'overview' ? 'primary' : 'default'" size="small" @click="activeChart = 'overview'"> 概览 </a-button>
        <a-button :type="activeChart === 'trend' ? 'primary' : 'default'" size="small" @click="activeChart = 'trend'"> 趋势 </a-button>
      </div>
    </div>

    <div class="charts-container">
      <!-- 数据概览图表 -->
      <div v-show="activeChart === 'overview'" class="chart-wrapper">
        <div ref="overviewChart" class="chart-container"></div>
      </div>

      <!-- 数据趋势图表 -->
      <div v-show="activeChart === 'trend'" class="chart-wrapper">
        <div ref="trendChart" class="chart-container"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { API_BASE_URL } from '@/utils/api'

const props = defineProps({
  userStats: {
    type: Object,
    default: () => ({
      articleCount: 0,
      totalViews: 0,
      totalLikes: 0,
      favoriteCount: 0,
      trendData: []
    })
  },
  loading: {
    type: Boolean,
    default: false
  }
})

const activeChart = ref('overview')
const overviewChart = ref(null)
const trendChart = ref(null)
let overviewChartInstance = null
let trendChartInstance = null

// 初始化概览图表
const initOverviewChart = () => {
  if (!overviewChart.value) return

  overviewChartInstance = echarts.init(overviewChart.value)

  const option = {
    title: {
      text: '数据概览',
      left: 'center',
      textStyle: {
        fontSize: 16,
        color: '#1d2129'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: '5%',
      left: 'center',
      itemGap: 20,
      textStyle: {
        fontSize: 12,
        color: '#515767'
      }
    },
    series: [
      {
        name: '数据分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '45%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          {
            value: props.userStats.articleCount || 0,
            name: '文章数量',
            itemStyle: { color: '#1e80ff' }
          },
          {
            value: Math.max(1, Math.floor((props.userStats.totalViews || 0) / 100)),
            name: '阅读量(百)',
            itemStyle: { color: '#52c41a' }
          },
          {
            value: props.userStats.totalLikes || 0,
            name: '点赞数',
            itemStyle: { color: '#fa8c16' }
          },
          {
            value: props.userStats.favoriteCount || 0,
            name: '收藏数',
            itemStyle: { color: '#eb2f96' }
          }
        ]
      }
    ]
  }

  overviewChartInstance.setOption(option)
}

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChart.value) return

  trendChartInstance = echarts.init(trendChart.value)

  // 从真实数据中提取趋势数据
  const trendData = props.userStats.trendData || []
  const days = []
  const viewsData = []
  const likesData = []
  const articlesData = []

  // 处理趋势数据
  trendData.forEach((item) => {
    const date = new Date(item.date)
    days.push(date.getMonth() + 1 + '/' + date.getDate())
    viewsData.push(item.views || 0)
    likesData.push(item.likes || 0)
    articlesData.push(item.articles_published || 0)
  })

  const option = {
    title: {
      text: '最近7天趋势',
      left: 'center',
      textStyle: {
        fontSize: 16,
        color: '#1d2129'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      bottom: '5%',
      left: 'center',
      textStyle: {
        fontSize: 12,
        color: '#515767'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: days,
      axisLabel: {
        color: '#8a919f',
        fontSize: 11
      },
      axisLine: {
        lineStyle: {
          color: '#e4e6ea'
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '阅读/点赞',
        position: 'left',
        axisLabel: {
          color: '#8a919f',
          fontSize: 11
        },
        axisLine: {
          lineStyle: {
            color: '#e4e6ea'
          }
        },
        splitLine: {
          lineStyle: {
            color: '#f2f3f5'
          }
        }
      },
      {
        type: 'value',
        name: '文章数',
        position: 'right',
        axisLabel: {
          color: '#8a919f',
          fontSize: 11
        },
        axisLine: {
          lineStyle: {
            color: '#e4e6ea'
          }
        }
      }
    ],
    series: [
      {
        name: '阅读量',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: '#1e80ff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(30, 128, 255, 0.3)'
              },
              {
                offset: 1,
                color: 'rgba(30, 128, 255, 0.05)'
              }
            ]
          }
        },
        data: viewsData
      },
      {
        name: '点赞数',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: '#52c41a'
        },
        data: likesData
      },
      {
        name: '发布文章',
        type: 'bar',
        yAxisIndex: 1,
        itemStyle: {
          color: '#fa8c16',
          borderRadius: [4, 4, 0, 0]
        },
        barWidth: '20%',
        data: articlesData
      }
    ]
  }

  trendChartInstance.setOption(option)
}

// 监听数据变化，更新图表
watch(
  () => props.userStats,
  (newStats) => {
    if (overviewChartInstance && activeChart.value === 'overview') {
      nextTick(() => {
        initOverviewChart()
      })
    }
    if (trendChartInstance && activeChart.value === 'trend') {
      nextTick(() => {
        initTrendChart()
      })
    }
  },
  { deep: true }
)

// 监听激活的图表切换
watch(activeChart, (newChart) => {
  nextTick(() => {
    if (newChart === 'overview' && !overviewChartInstance) {
      initOverviewChart()
    } else if (newChart === 'trend' && !trendChartInstance) {
      initTrendChart()
    }

    // 重新调整图表大小
    setTimeout(() => {
      if (newChart === 'overview' && overviewChartInstance) {
        overviewChartInstance.resize()
      } else if (newChart === 'trend' && trendChartInstance) {
        trendChartInstance.resize()
      }
    }, 100)
  })
})

// 窗口大小变化时重新调整图表
const handleResize = () => {
  if (overviewChartInstance) {
    overviewChartInstance.resize()
  }
  if (trendChartInstance) {
    trendChartInstance.resize()
  }
}

onMounted(() => {
  nextTick(() => {
    initOverviewChart()
    window.addEventListener('resize', handleResize)
  })
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)

  if (overviewChartInstance) {
    overviewChartInstance.dispose()
    overviewChartInstance = null
  }
  if (trendChartInstance) {
    trendChartInstance.dispose()
    trendChartInstance = null
  }
})
</script>

<style scoped>
.user-stats-chart {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.stats-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1d2129;
}

.chart-tabs {
  display: flex;
  gap: 8px;
}

.charts-container {
  width: 100%;
  height: 300px;
}

.chart-wrapper {
  width: 100%;
  height: 100%;
}

.chart-container {
  width: 100%;
  height: 100%;
}

@media (max-width: 768px) {
  .charts-container {
    height: 250px;
  }

  .stats-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .chart-tabs {
    align-self: stretch;
    justify-content: center;
  }
}
</style>
